//********************************************************************************************************
// Product Name: MapWindow.dll Alpha
// Description:  The core libraries for the MapWindow 6.0 project.
//
//********************************************************************************************************
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); 
// you may not use this file except in compliance with the License. You may obtain a copy of the License at 
// http://www.mozilla.org/MPL/ 
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF 
// ANY KIND, either expressed or implied. See the License for the specificlanguage governing rights and 
// limitations under the License. 
//
// The Original Code is MapWindow.dll
//
// The Initial Developer of this Original Code is Ted Dunsford. Created in August, 2007.
// 
// Contributor(s): (Open source contributors should list themselves and their modifications here). 
//
//********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using MapWindow.Drawing;
using MapWindow.Geometries;
using MapWindow.Main;
namespace MapWindow.DirectX
{
    /// <summary>
    /// This is a class that organizes a list of renderable layers into a single "view" which might be
    /// shared by multiple displays.  For instance, if you have a map control and a print preview control,
    /// you could draw the same data frame property on both, just by passing the graphics object for each.
    /// Be sure to handle any scaling or translation that you require through the Transform property
    /// of the graphics object as it will ultimately be that scale which is used to back-calculate the
    /// appropriate pixel sizes for point-size, line-width and other non-georeferenced characteristics.
    /// </summary>
    public class MapFrameDX : LayerFrame, IMapFrameDX
    {
        


        #region Private Variables

        private bool _isPaintingCancelled;
       
        private bool _hasBeenSetup;


        #endregion

        #region Constructors

        /// <summary>
        /// The Constructor for the MapFrame object
        /// </summary>
        public MapFrameDX()
        {
            Configure();
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="container"></param>
        protected MapFrameDX(ICollection<ILayer> container)
        {
            container.Add(this);
            Layers = new LayerCollectionDX(this);
            Configure();

        }

        private void Configure()
        {
            base.MapFrame = this;
            Layers = new LayerCollectionDX(this);

        }

        

       
        //private void ZoomToMapFrame_Click(object sender, EventArgs e)
        //{
        //    this.Extents = this.Envelope;
        //}

       

       

        
       
       

        
        
      
        #endregion

        #region Methods

        /// <summary>
        /// Selects a layer
        /// </summary>
        public void SelectLayer()
        {
            
        }


        /// <summary>
        /// This is the internal drawing method that follows the standard checks.  Drawing is evoked
        /// through the Draw3D command, but internally implemented in the DrawPart method.  After
        /// the initial checks, the Draw3D method will cycle the part integer from 0 to NumParts -1.
        /// </summary>
        /// <param name="args">A DrawArgsDX class with the device and camera.</param>
        protected virtual void OnDraw(DrawArgsDX args)
        {
            Layers[args.Part].Draw3D(args);
        }
      




        /// <summary>
        /// Overrides the group creation to make sure that the new group will cast its layers
        /// to the appopriate geoLayer type.
        /// </summary>
        protected override void OnCreateGroup()
        {
            GroupDX grp = new GroupDX(Layers, this, ProgressHandler);
            grp.LegendText = "New Group";
        }

        /// <summary>
        /// Occurs before each draw cycle and test whether we need to zoom in the coordinate system of floating point vertices or not.
        /// </summary>
        /// <param name="e">A DrawSetupArgs Event Argument containing information about the drawing</param>
        protected virtual void OnDrawSetup(DrawSetupArgs e)
        {
            if (_hasBeenSetup == false)
            {
                e.Camera.ResetDrawBox();
                _hasBeenSetup = true;
            }
            Vector v = e.Camera.CameraLocation.Subtract(e.Camera.TargetLocation);
            decimal z = Math.Abs(Convert.ToDecimal(v.Z));
            if (z * 100 < e.Camera.DrawBox.XSpan)
            {
                e.Camera.ResetDrawBox();
            }
            else if (z / 100 > e.Camera.DrawBox.XSpan)
            {
                e.Camera.ResetDrawBox();
            }
        }

        #endregion

        #region Properties

      

        /// <summary>
        /// This propogates the cancel message down through the drawing levels
        /// to ensure that the current drawing action is terminated as soon
        /// as possible in order to exit gracefully.
        /// </summary>
        public virtual bool IsPaintingCancelled
        {
            get { return _isPaintingCancelled; }
            set
            {
                _isPaintingCancelled = value;
                
            }
        }

      
        /// <summary>
        /// The envelope that contains all of the layers for this data frame.  Essentially this would be
        /// the extents to use if you want to zoom to the world view.
        /// </summary>
        public override MapWindow.Geometries.IEnvelope Envelope
        {
            get
            {
                if (Layers == null || Layers.Count == 0) return null;
                IEnvelope env = Layers[0].Envelope;
                if (env == null) return new Envelope();
                foreach(ILayerDX layer in Layers)
                {
                    env.ExpandToInclude(layer.Envelope);
                }
                return env;
            }
           
        }

        /// <summary>
        /// Gets or sets the layers
        /// </summary>
        public new ILayerCollectionDX Layers
        {
            get { return base.Layers as ILayerCollectionDX; }
            set { base.Layers = value as ILayerCollection; }
        }

   

      

    


        #endregion

        #region Protected Methods

      

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            //if (disposing && (components != null))
            //{
            //    components.Dispose();
            //}
            base.Dispose(disposing);
        }


    
        /// <summary>
        /// The number of parts for a MapFrame is the number of layers on the map.
        /// </summary>
        public virtual int NumParts
        {
            get
            {
                return Layers.Count;
            }
            protected set
            {
                // does nothing
            }
        }
       

        #endregion

       


        #region ILegendItem Members

        /// <summary>
        /// Paints the legend symbol
        /// </summary>
        /// <param name="g">The System.Drawing.Graphics surface to draw on</param>
        /// <param name="box">A rectangular box to draw in</param>
        public override void LegendSymbol_Painted(Graphics g, Rectangle box)
        {
            g.DrawIcon(ImageResources.Layers, box);
        }

   

    
        ///// <summary>
        ///// Returns the layers, but only as ILegendItems
        ///// </summary>
        //IChangeEventList<ILegendItem> ILegendItem.LegendItems
        //{
        //    get { return (IChangeEventList<ILegendItem>)_layers; }
        //}

    
   

       
        #endregion

        #region RenderBase

        #region Events

        /// <summary>
        /// Occurs immediately before drawing, allowing it to be cancelled
        /// </summary>
        public event EventHandler<DrawVerifyArgsDX> BeforeDrawing;

        /// <summary>
        /// Occurs after drawing, indicating if an exception or cancellation occured
        /// </summary>
        public event EventHandler<DrawCompletedArgsDX> DrawingCompleted;


        /// <summary>
        /// Occurs when the data has been loaded into the model after the first drawing method
        /// </summary>
        public event EventHandler<DrawArgsDX> Inititialized;

   
       

        #endregion

        #region Private Variables

        /// <summary>
        ///  Boolean, determines if this is visible or not
        /// </summary>

        private int _numStages = 1;
      
        #endregion

        #region Methods

      
        

        /// <summary>
        /// Causes the layer or object to draw itself to the map.  This may initiate
        /// one-time loading of buffers, but should not do heavy calculations every
        /// cycle.
        /// </summary>
        /// <param name="args">A Drawing Args structure.  This is used so that this method
        /// can also be called asynchronously</param>
        public virtual void Draw3D(DrawArgsDX args)
        {
           // try
           // {
                if (IsVisible == false)
                {
                    OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
                    return;
                }
                if (OnBeforeDrawing(new DrawVerifyArgsDX(args, false)) == true)
                {
                    OnDrawingCompleted(new DrawCompletedArgsDX(args, true, null));
                    return;
                }

                OnDrawSetup(new DrawSetupArgs(args.Camera));
                args.Camera.Position(args.Device);
                
                if (IsInitialized == false)
                {
                    Initialize(args);
                }

               


                for (int stage = 0; stage < NumStages; stage++)
                {
                    for (int part = 0; part < NumParts; part++)
                    {
                        DrawArgsDX innerArgs = new DrawArgsDX(args.Device, args.Camera, part, stage);
                        OnDraw(innerArgs);
                    }
                }
                OnDrawingCompleted(new DrawCompletedArgsDX(args, false, null));
            //}
            //catch (Exception ex)
            //{
            //    OnDrawingCompleted(this, new DrawCompletedArgsDX(args, false, ex));
            //}


        }

        /// <summary>
        /// This handles the initialization where structures are created
        /// </summary>
        public virtual void Initialize(DrawArgsDX args)
        {
            // setup occurs here
            OnInitialize(args);
        }

      
        /// <summary>
        /// Determines the geographic distance to use for something that is one pixel wide on the screen
        /// </summary>
        /// <param name="args">A DrawArgsDX with a Microsoft.DirectX.Device</param>
        /// <returns>A float multiplier for the scale</returns>
        public float GetScale(DrawArgsDX args)
        {
            Viewport vp = args.Device.Viewport;
            Transforms t = args.Device.Transform;
            // Find the point along the view path of the camera that intersects with the 0 elevation of the z plane
            //Vector3 pt = Plane.IntersectLine(args.Camera.XYPlane, args.Camera.CameraPosition, args.Camera.TargetPosition);
            Vector3 pt = Vector3.Subtract(args.Camera.TargetPosition, args.Camera.CameraPosition);
            float z = Math.Abs(args.Camera.CameraPosition.Z);
            pt.X = pt.X * z / pt.Z;
            pt.Y = pt.Y * z / pt.Z;
            pt = Vector3.Add(args.Camera.CameraPosition, pt);
            pt.Z = 0;

            // Project that into screen space in order to determine where the 0-elevation plane is between the near plane an the far plane of the scene
            Vector3 depth = Vector3.Project(pt, vp, t.Projection, t.View, t.World);

            // Back project two pixels from the screen into world coordinates that are separated by a distance of 1 pixel
            Vector3 center = new Vector3(vp.Width / 2, vp.Height / 2, depth.Z);
            Vector3 right = new Vector3(vp.Width / 2 + 1, vp.Height / 2, depth.Z);
            Vector3 wCenter = Vector3.Unproject(center, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);
            Vector3 wRight = Vector3.Unproject(right, vp, args.Device.Transform.Projection, args.Device.Transform.View, args.Device.Transform.World);
            
            // The distance between the two locations in world coordinates gives a scale value.
            Vector3 diff = Vector3.Subtract(wRight, wCenter);
           
            return diff.Length();
        }

       

        #endregion

        #region Properties

        
       

       

    

        /// <summary>
        /// Gets the number of stages that will be drawn.  Each stage cycles through every part.
        /// </summary>
        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public virtual int NumStages
        {
            get { return _numStages; }
            protected set { _numStages = value; }
        }




        #endregion

        #region Protected Methods



     

        /// <summary>
        /// Fires the event that occurs before drawing to a directX map
        /// </summary>
        /// <param name="e">The DrawVerifyArgsDX parameter with information about the drawing</param>
        /// <returns>Boolean, that if true should cancel the draw event.</returns>
        protected virtual bool OnBeforeDrawing(DrawVerifyArgsDX e)
        {
            if (BeforeDrawing == null) return false;
            BeforeDrawing(this, e);
            return e.Cancel;
        }

      
      
        /// <summary>
        /// Fires an event when we are done with the drawing code, whether the drawing was successful, cancelled, or threw an exception.
        /// </summary>
        /// <param name="e">A DrawCompletedArgsDX parameter containing information about the drawing</param>
        protected virtual void OnDrawingCompleted(DrawCompletedArgsDX e)
        {
            if (DrawingCompleted == null) return;
            DrawingCompleted(this, e);
        }

 

        /// <summary>
        /// Fires the Initialized event
        /// </summary>
        /// <param name="e">An EventArgs parameter</param>
        protected virtual void OnInitialize(DrawArgsDX e)
        {
            IsInitialized = true;
            if (Inititialized != null)
            {
                Inititialized(this, e);
            }
            
        }


        #endregion

        #endregion


    }
}
